package com.mangguo.tingjian.util;

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.csv.CSVFormat;
import org.apache.commons.csv.CSVPrinter;

import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLEncoder;
import java.util.List;

@Slf4j
public class CvsUtils {
    public static void  downloadCvs(HttpServletResponse response,String fileName, List<List<String>> rows){

        try(Writer  writer = new BufferedWriter(new OutputStreamWriter(response.getOutputStream(), "UTF-8"));
            CSVPrinter printer = CSVFormat.EXCEL.print(writer)){

            response.setHeader("content-type", "application/octet-stream");
            response.setContentType("application/octet-stream");
            // 下载文件能正常显示中文
            response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(fileName + ".csv", "UTF-8"));
            // 写入bom头
            byte[] uft8bom={(byte)0xef,(byte)0xbb,(byte)0xbf};
            response.getOutputStream().write(uft8bom);
            for (List<String> row : rows) {
                printer.printRecord(row);
            }
            printer.flush();
        }catch (Exception e){
            log.error("文件下载错误", e);
        }
        
    }
}
